package com.qys.livesMall.event.listener;


import cn.hutool.core.bean.BeanUtil;
import com.qys.livesMall.app.user.event.LimitEvent;
import com.qys.livesMall.app.user.model.entity.Limit;
import com.qys.livesMall.app.user.model.pojo.LimitCachePOJO;
import com.qys.livesMall.app.user.model.pojo.UserLimitEventPOJO;
import com.qys.livesMall.app.user.service.LimitService;
import com.qys.livesMall.cache.RedisCache;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;

import static com.qys.livesMall.app.user.constants.RedisConstant.LIMIT_USER;

@Slf4j
@Component
public class LimitListener implements ApplicationListener<LimitEvent> {

    @Resource
    private RedisCache redisCache;
    @Resource
    private LimitService limitService;


    @Async
    @Override
    public void onApplicationEvent(LimitEvent event) {
        UserLimitEventPOJO pojo = (UserLimitEventPOJO) event.getSource();
        List<Long> userIds = pojo.getUserIds();
        userIds.forEach(e -> {
            Limit limit = limitService.getByUserIdAndLimitUrlId(e, pojo.getLimitUrlId());
            limit.setStatus(pojo.getStatus());
            limitService.updateById(limit);
            List<Limit> limitList = limitService.processLimit(e);
            redisCache.setCacheObject(LIMIT_USER + e, BeanUtil.copyToList(limitList, LimitCachePOJO.class));
        });
    }
}
